import sys
import array as A
import datetime as DT
from dateutil.parser import parse as dateparse
from telnetlib import Telnet as T
from socket import timeout
import tkMessageBox as MB

def timeout_exception(msg):
	t, v, b = sys.exc_info()
	MB.showerror("Sorry!", msg + str(t) + " " + str(v) + "\n" + str(b))
	
def getdata(ipport, max):
	tn, out, date, time = (None, None, None, None)
	host, port = ipport
	prompt = "S>"
	attempts = 1
	try: 
		tn = T(host, port, max)
		tn.write("\r\n")
		tmp = tn.read_until(prompt, max); out = tmp; 
		print
		print tmp
		print
		if prompt not in out:
			raise timeout
#	except EOFError:
	
	except timeout:
		timeout_exception("Couldn't get a prompt in " + str(max) + 
		" tries.  Giving up.\n")
		return (tn, out, date, time)

	try:
			# Send stops 'til server says "status = not logging"
		print
		print "Connection established, issuing stop command"
		print
		tn.write("stop\r\n")
		tmp = tn.read_until(prompt, max); out += tmp; 
		print
		print tmp
		print
		tn.write("ds\r\n")
#		tmp = tn.read_until("not", max); print tmp
		ju, nk, up2match = tn.expect(["logging"], max); 
		print
		print "up2match = ", up2match
		print
			# Get type (16 or 37)
		type_determiner = up2match.split('V')[0]
		print
		print type_determiner
		print
		if "16" in type_determiner:
			typ = "16"
		elif "37" in type_determiner:
			typ = "37"
		else:
			MB.showerror("Sorry!", "Instrument type not recognized!")
			return (tn, out, date, time)
		print
		print "typ = ", typ
		print		
		while ("not logging" not in up2match) and (attempts < max):
			if attempts == 1:
				print
				print "In while loop looking for a not logging"
				print
			attempts += 1
			tn.write("stop\r\n")
			tmp = tn.read_until(prompt, max); 
			print tmp
			tn.write("ds\r\n")
#			tmp = tn.read_until("status = ", max); print tmp
			ju, nk, up2match = tn.expect(["logging"], max); # print up2match
			print "up2match = ", up2match
		if attempts >= max: # if there were too many attempts
			raise timeout # raise a timeout exception
	except timeout:
		timeout_exception("Server wouldn't stop logging in " + str(max) + 
			" tries.  Giving up.\n")
		return (tn, out, date, time)

	try: # if we get here, we successfully read a "not logging"
		print
		print "ds returned a status of not logging, proceding"
		print
		tn.write("\r\n")
		tmp = tn.read_until(prompt, max); 
		print
		print tmp
		print
		tn.write("ds\r\n")
		if "16" in typ:
			ju, nk, tmp = tn.expect(["\d\d\s\w\w\w\s\d\d\d\d"], max)
		else:
			ju, nk, tmp = tn.expect(["\d\d-\d\d-\d\d\d\d"], max)
		out += tmp; print out[-11:], dateparse(out[-11:])
		date = dateparse(out[-11:])
		if date is None:
			raise timeout
		tmp = tn.read_until("\r\n", max); out += tmp; 
		print "Time = ", tmp
		time = dateparse(out[-10:-3])
		if "16" in typ:
			lookfor = "samples = "
		else:
			print
			print "Took the 37 branch"
			print
			lookfor = "samplenumber = "
		tmp = tn.read_until(lookfor, max); out += tmp; 
		print tmp
		tmp = tn.read_until(',', max); out += tmp; 
		print tmp
		ns = int(tmp.strip(','), 10)
		print
		print "# of samples: ", ns
		print
	except ValueError:
		t, v, b = sys.exc_info()
		if "invalid literal" in str(v):
			MB.showerror("Sorry!", 
				"Error converting number of samples to an integer.\n" + 
				str(t) + "; " + str(v) + ";\n" + str(b))
		else:
			MB.showerror("Sorry!", 
				"Unknown ValueError reading or converting number of samples.\n" + 
				str(t) + "; " + str(v) + ";\n" + str(b))
		return (tn, out, date, time)
	except timeout:
		timeout_exception("Couldn't get number of samples in " + str(max) + 
			" tries.  Giving up.\n")
		return (tn, out, date, time)

	try: # have number of samples, get rest of header...
		print
		print "Date, time, and number of samples read"
		print
		tmp = tn.read_until(prompt, max); out += tmp; 
		print tmp
		# ...and the decimal data
		range = "dd0,96\r\n" # this is the default	
		if ns >= 96: # this is the more likely event
			range = "dd" + str(ns-96) + "," + str(ns) + "\r\n"
		tn.write(range)
		tmp = tn.read_until(prompt, max); out += tmp; 
		print tmp
	except timeout:
		timeout_exception("Couldn't get either rest of header or the decimal data" + 						  "in " + str(max) + " tries.  Giving up.\n")
		return (tn, out, date, time)
		
	try: # now get hex data
		print "Got header and decimal data"
		if "16" in typ:
			fmtcmd = "outputformat=1\r\n"
		else:
			print
			print "Took the 37 branch"
			print
			fmtcmd = "format=0\r\n"
		tn.write(fmtcmd) # change the output format to hex
		tmp = tn.read_until(prompt, max); out += tmp; 
		print tmp
		tn.write(range)
		tmp = tn.read_until(prompt, max); out += tmp; 
		print tmp
		if "16" in typ:
			fmtcmd = "outputformat=3\r\n"
		else:
			print
			print "Took the 37 branch"
			print
			fmtcmd = "format=2\r\n"
		tn.write(fmtcmd) # change the output format back to dec
		tmp = tn.read_until(prompt, max); out += tmp; 
		print tmp
	except timeout:
		timeout_exception("Couldn't get the hex data in " + str(max) +  
			" tries.  Giving up.\n" )
	finally:
		return (tn, out, date, time)